import cv2

# 设置摄像头为 YUYV422 格式
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)

# 手动设置分辨率（必须与摄像头支持的格式匹配）
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('Y', 'U', 'Y', 'V'))  # 设置 YUYV
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)   # 宽度
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)  # 高度

# 加载人脸检测器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

while True:
    ret, frame = cap.read()
    if not ret:
        print("Failed to capture frame")
        break

    # 将帧转换为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 检测人脸
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    # 在检测到的人脸周围绘制矩形
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    cv2.imshow("YUYV422 Camera with Face Detection", frame)
    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
